function pfhtml(filen, bspec)
% pf: print the file details to html/window
%     2 usages: 1) pf<cr>  asks for a file
%               2) pf filename lists index of selected file.
%					 3) pf(filename, 'data') provides information on the data blocks
%    						in the file, likewise for 'sf', 'df', 'note', 'header'
%
% opens the file and loades the index...
% and lists contents to matlab window
% pf is derived from lif, but lists more information
%

htmlfile = [];
if(nargin < 1)
   filen = [];
end;
shortflag = 0;
if(strcmp(filen, '-s'))
   shortflag = 1; % inverted flag for "short" listing.
   filen = [];
end;
if(nargin < 2)
   bspec = []; % block specification (to pick certain block types)
else
   if(~strmatch(lower(bspec), {'data', 'sf', 'df', 'note', 'header'}, 'exact'))
      fprintf(2, 'block spec type %s not recognized\n', bspec);
      return;
   end;
end;

[p f e] = fileparts(filen);
filename = fullfile(p, [f e]);

if(~shortflag)
   fid = fopen(filename, 'r');
   if(fid < 0)
	   QueMessage(sprintf('File %s NOT FOUND', filename), 1);
   return;
end;
else
   fclose(fid);
end;


if(strcmp(e, '.not')) % old datac notefile - put up the window with the raw notefile in it.
   fid = fopen(filename, 'rt');
   if (fid == -1)
      QueMessage(sprintf('%s not found.', filename));
      return
   end
   [p f e] = fileparts(filename);
   htmlfile = fullfile(pathname, [f '.html']); % make an html filename
   disp_list = {};
   while (~feof(fid))
      new_line = fgetl(fid);
      if (new_line == -1)
         break
      else
         disp_list{end + 1} = new_line;
      end
   end
   if(~isempty(disp_list))
      hhtm = fopen(htmlfile, 'w'); % overwrites previous by this name.
      fprintf(hhtm, '<html>\n<head>\n<title>Notefile for %s</title>\n', filename);
      fprintf(hhtm, '<meta http-equiv=\"Content-Type\" content=\"text/html;charset=iso-8859-1\">');
      fprintf(hhtm, '</head><body><a NAME=\"Top\"></a><font size = "3"><pre>\n');
      noteflag = 0;
      for i = 1: length(list)
         fprintf(hhtm, '%s<br>', list{i});
      end;
      
      fprintf(hhtm, '</font></pre></body>\n</html>');
      fclose(hhtm);
      % launch browser to read the file...
      dos (sprintf('c:\\progra~1\\netscape\\communicator\\program\\netscape.exe %s &', ...
         htmlfile));
      return;
   end;  
end; 

% display mat files.
nfile = 1;

if(isempty(filename))
   if(exist('pfhtml.ini') == 2)
      hp = fopen('pfhtml.ini', 'r');
      inipath = fgetl(hp);
      if(~exist('inipath', 'dir')) % find out if path still exists...
         inipath = '';
      end;
      fclose(hp);
   else
      inipath = '';
   end;
   
   if(~exist('INDEX.mat', 'file'))
      [filenames, pathname] = uigetfiles([inipath '*.mat'], 'File for listing?');
      hp = fopen('pfhtml.ini', 'w');
      fprintf(hp, '%s', pathname);
      fclose(hp);
      if(isempty(filenames))
         return;
      end;
      if(length(filenames) == 1)
         [p f e] = fileparts(filenames{1});
         htmlfile = fullfile(pathname, [f '.html']); % make an html filename
      else
         htmlfile = 'DIRECTORY.html';
         nfile = length(filenames);
      end;
   else
      filename = 'INDEX';
   end;
   if(nfile == 1)
      filenames{1} = [pathname, filename];   
   end;
end;
if(isempty(htmlfile))
	[pathname f e] = fileparts(filename);
   html_wd = [pwd '\html'];
   htmlfile = fullfile(html_wd, [f '.html']); % make an html filename
end;
      
hhtm = fopen(htmlfile, 'w'); % overwrites previous by this name.
if(nfile == 1)
   fprintf(hhtm, '<html>\n<head>\n<title>Notefile for %s</title>\n', filename);
   fprintf(hhtm, '<meta http-equiv=\"Content-Type\" content=\"text/html;charset=iso-8859-1\">');
   fprintf(hhtm, '</head><body><a NAME=\"Top\"></a><font size = "2"><pre>\n');
else
   fprintf(hhtm, '<html>\n<head>\n<title>Notefiles</title>\n');
   fprintf(hhtm, '<meta http-equiv=\"Content-Type\" content=\"text/html;charset=iso-8859-1\">');
   fprintf(hhtm, '</head><body><a NAME=\"Top\"></a><font size = "2"><pre>\n');
end;

for i = 1:nfile
   if(nfile > 1)
      filename = [pathname, char(filenames{i})];
   end;
      
   
   v=[];
   if(exist(filename) == 2)
      v = load(filename, 'Index');
   else
      fprintf('File %s not found?\n', filename);
      return;
   end;
   if(isempty(fieldnames(v)))
      v=load('INDEX'); % maybe file is not closed
      if(isempty(fieldnames(v)))
         fprintf(2, 'lif: No index associated with file %s\n', filename);
         return;
      end;
   end;
   
   element = fieldnames(v);
   INDEX = eval(['v.' char(element)]);
   list = {};
   list = cellcat(list, sprintf('<h4>File: %s</h4>', filename));
   load(filename, 'HFILE'); % get the header information.
   list = cellcat(list, sprintf('<h5>Signature: %s</h5>', char(HFILE.Signature.v)));
   list = cellcat(list, sprintf('Species: %s  Age: %s Wt: %s  Sex: %s', char(HFILE.Species.v), ...
      char(HFILE.Age.v), char(HFILE.Weight.v), char(HFILE.Sex.v)));
   c=char(HFILE.Experiment.v);
   list = cellcat(list, '<h5>Experiment:</h5>');
   for j = 1:size(c,1)
      if(length(c(j,:)) > 0 & ~all(isspace(c(j,:))))
         list = cellcat(list, sprintf('%s', c(j,:)));
      end;
   end;
            list = cellcat(list, '<hr>');
if(~shortflag)
         list = cellcat(list, sprintf('Index for File: %s  ', filename));
         s = length(INDEX);
         list = cellcat(list, sprintf('    Date      Time     Block   Rec         Type         Info          Name'));    
         list = cellcat(list, sprintf('---------------------------------------------------------------------------'));
         for i = 1:s
            if(isempty(bspec))
               list = cellcat(list, sprintf('%8s  %8s  %4d  %4d  %12s  %12s  %12s', ...
                  INDEX(i).date, INDEX(i).time, INDEX(i).block, INDEX(i).record, INDEX(i).type, INDEX(i).type2, INDEX(i).MatName));
            else
               if(strmatch(lower(bspec), lower(INDEX(i).type), 'exact'))
                  list = cellcat(list, sprintf('%8s  %8s  %4d  %4d  %12s  %12s  %12s', INDEX(i).date, INDEX(i).time, INDEX(i).block, INDEX(i).record, INDEX(i).type, INDEX(i).type2, INDEX(i).MatName));
               end;
            end;
            
         end;
      else
         
         list = cellcat(list, '<hr>');
         list = cellcat(list, sprintf('  Date    Block   Records  Mode   Protocol    Sequence            Par  Par#'));    
         list = cellcat(list, '<hr>');
      end;
      
      data_blks = strmatch('DATA', char(INDEX.type), 'exact');
      notes = strmatch('NOTE', char(INDEX.type), 'exact');
      note_blks = [INDEX(notes).block]; % identify these by the BLOCK number itself...
      data_blks = union(data_blks, notes); % identify indices to all blocks we need to access
      % now for each element of the input index, print some information
      done_blk = [];
      for indxi = 1:length(data_blks) % look for the data in all the blocks (it doesn't hurt to search)
         ind = data_blks(indxi);
         this_block = INDEX(ind).block;
         dblk = [];
         if(~isempty(done_blk)) % just prevent warning message
            dblk = find(this_block == done_blk); % check to see if we have already processed block number (union may return multiple indices for same block)
         end;
         if(isempty(dblk))
            done_blk = [done_blk this_block]; % add (provisionally) finished block to the list
            this_time = INDEX(ind).time;
            [sfile, df, notes] = block_info(filename, this_block);
            if(~shortflag)
               list = cellcat(list, '<hr>');
               binfo = sprintf('<th><h6>BLOCK: %d started at %8s, contains', ...
                  this_block, this_time);
               list = cellcat(list, sprintf('%s records: %d-%d</th>', binfo, INDEX(ind-1).record, INDEX(ind).record));
               
               if(~isempty(df) & ~ isempty(sfile))
                  list = cellcat(list, '<table  cellspacing=\"1\" cellpadding=\"1\" border=\"1\">');
                  if(length(df.Filename.v) == 0 | isempty(df.Filename.v) | all(isspace(df.Filename.v)))
                     fnm = '**auto**';
                  else
                     fnm = df.Filename.v;
                  end;
                  list = cellcat(list, sprintf('<tr><td><tt><font size = -1>Stimulus: %s </font></td><td> </td><td><tt><font size = -1>Acquisition: %s</font></td><td> </td></tr>', ...
                     sfile.Name.v, fnm));
                  list = cellcat(list, sprintf('<tr><td><tt><font size = -1>Sequence: %s</font></tt></td><td><tt><font size = -1>SeqPar: %s</font></tt></td><td><tt><font size = -1>Rate: %6.2f</font></tt></td><td><tt><font size = -1>Points: %d</font></tt></td></tr>',...
                     sfile.Sequence.v, sfile.SeqParList.v, df.Sample_Rate.v, df.Points.v));
                  list = cellcat(list, sprintf('<tr><td><tt><font size = -1>Repeat: %d</font></td><td><tt><font size = -1>SeqN %d</font></td><td><tt><font size = -1>Cycle %s</font></td><td><tt><font size = -1>Mode: %s</font></td></tr>',...
                     sfile.Repeats.v, sfile.Stim_Repeat.v, sfile.Cycle.v, df.Data_Mode.v));
                  
                  si = sfile.Superimpose.v;
                  if(length(si) == 0)
                     si = '**none**';
                  end;
                  ac=sfile.Addchannel.v;
                  if(length(ac) == 0)
                     ac = '**none**';
                  end;
                  chl = '[';
                  for ii = 1: length(df.Channels.v)
                     chl = strcat(chl, sprintf(' %2d ', df.Channels.v(ii)));
                  end;
                  chl = strcat(chl, ']');
                  gl = '[';
                  for ii = 1: length(df.Amplifier_Gain.v)
                     gl = sprintf('%s%4.1f', gl, df.Amplifier_Gain.v(ii));
                  end;
                  gl = strcat(gl, ']');
                  
                  list = cellcat(list, sprintf('<tr><td><tt><font size = -1>Superimpose: %s</font></td><td><tt><font size = -1>AddChannel: %s</font></tt><td><tt><font size = -1>Gain: %s</font></td><td><tt><font size = -1>Channels: %s</font></td></tr>', ...
                     si, ac, gl, chl));
                  list = cellcat(list, '</table>');
               end;
            else
               if(~isempty(df) & ~ isempty(sfile))
                  fnsfile = fieldnames(sfile);
                  if(strmatch(fnsfile, 'SeqStepList'))
                     sfarg = sfile.SeqStepList.v;
                  elseif(strmatch(fnsfile, 'SeqLevelList'))
                     sfarg = sfile.SeqLevelList.v;
                  else
                     sfarg = 0;
                  end;
                  binfo = sprintf('<tt>%8s: %3d [%4d-%4d] %3s: %-12s %-20s %-6s %2d', ...
                     this_time, this_block, INDEX(ind-1).record, INDEX(ind).record, df.Data_Mode.v, sfile.Name.v, sfile.Sequence.v, ...
                     sfile.SeqParList.v, sfarg);
                  list = cellcat(list, sprintf('%s', binfo ));
               end;
               
               
            end;
            
            if(~isempty(notes))
               for i = 1:length(notes)  % notes{1}.v
                  c=char(notes{i}.v);
                  if(strmatch(fieldnames(notes{1}), 't'))
                     list = cellcat(list, sprintf('Note (%2d:%2d:%2.0f):', ...
                        notes{1}.t(4), notes{1}.t(5), notes{1}.t(6)));
                  end;
                  for j = 1:size(c,1)
                     if(length(c(j,:)) > 0 & ~all(isspace(c(j,:))))
                        if(j == 1)
                           o = linebreak(c(j,:));
                           
                           list = cellcat(list, sprintf('Note:  %s', o));
                        else
                           o = linebreak(c(j,:));
                           
                           list = cellcat(list, sprintf('       %s', o));
                        end;                     
                     end;
                  end;
                  list = cellcat(list, '<hr>');
               end;
            end;         
         end;   
      end;
      
      noteflag = 0;
      for i = 1: length(list)
         if(findstr(list{i}, 'DATA'))
            dnp = findstr(list{i}, 'db_');
            id = sscanf(list{i}(dnp:end), 'db_%d'); % get the number, create a link to the tag
            fprintf(hhtm, '<a href=\"#blk_%d\"><b>%s</b></a><br>', id, list{i});
         elseif (findstr(list{i}, 'BLOCK:'))
            dnp = findstr(list{i}, 'BLOCK:'); % create the block tag here too (target).
            id = sscanf(list{i}(dnp:dnp+9), 'BLOCK: %d');
            fprintf(hhtm, '<a NAME=\"blk_%d\"><b>%s</b></a> <a href=\"#Top\">^</a><br>', id, list{i});
            
         elseif(~isempty(findstr(list{i}, '********'))) % turn off noteflag stuff
            noteflag = 0;
            fprintf(hhtm, '<font color=#000000>%s<br>', list{i});
         elseif (~isempty(findstr(list{i}, 'Note:'))) % when in a note, italic/bold.
            if(~shortflag)
               fprintf(hhtm, '<font color=#0000ff><i>%s</i><br>', list{i});
            else
               fprintf(hhtm, '<font color=#000000><i>%s</i><br>', list{i});
            end;
            
            noteflag = 1;
         else
            fprintf(hhtm, '%s<br>', list{i});
         end;
      end;
      fprintf(hhtm, '<hr>');
      fprintf(hhtm, '</font></pre>');
   end;
   fprintf(hhtm, '</body>\n</html>');
   fclose(hhtm);
   % launch browser to read the file...
   %dos (sprintf('c:\\progra~1\\netscape\\communicator\\program\\netscape.exe %s &', ...
   %   htmlfile));
   web(sprintf('file:%s', htmlfile));
   
   return;
   
   
   function [sfile, df, notes] = block_info(filename, wblk)
   
   sfile=[];
   df=[];
   notes={};
   sfc = sprintf('sf%d', wblk);
   sfile = load(filename, sfc); % read the stim block
   if(~isempty(fieldnames(sfile)))
      sfile = eval(['sfile.' sfc]);
      dfc = sprintf('df%d', wblk);
      df = load(filename, dfc); % read the data block
      df = eval(['df.' dfc]);
   else
      sfile = [];
      df = [];
   end;
   nfc = sprintf('Note%d_*', wblk);
   nf = load(filename, nfc);
   if(~isempty(fieldnames(nf)))
      fn = fieldnames(nf);
      for i = 1:length(fn)
         notes{i}.v = eval(['nf.' fn{i} '.v']);
         %      notes{i}.t = eval(['nf.' fn{i} '.t']);
      end;
   end;
   return;
   
   function [o] = cellcat(in, string)
   o = in;
   p = length(in) + 1;
   o{p} = string;
   return;
   
   
   